# 基础镜像阶段
FROM swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/node:20.14.0-alpine AS base

# 设置工作目录
WORKDIR /app

# 依赖阶段 - 安装所有依赖
FROM base AS dependencies
COPY package.json package-lock.json ./
RUN npm ci

# 构建阶段 - 构建应用
FROM base AS builder
COPY --from=dependencies /app/node_modules ./node_modules
COPY . .

# 设置构建时环境变量
ARG NEXT_PUBLIC_MQTT_HOST=113.45.136.1
ARG NEXT_PUBLIC_MQTT_PORT=8083
ARG NEXT_PUBLIC_MQTT_USERNAME=admin
ARG NEXT_PUBLIC_MQTT_PASSWORD=admin123
ARG NEXT_PUBLIC_MQTT_PROTOCOL=ws

# 使构建参数可用作环境变量
ENV NEXT_PUBLIC_MQTT_HOST=${NEXT_PUBLIC_MQTT_HOST}
ENV NEXT_PUBLIC_MQTT_PORT=${NEXT_PUBLIC_MQTT_PORT}
ENV NEXT_PUBLIC_MQTT_USERNAME=${NEXT_PUBLIC_MQTT_USERNAME}
ENV NEXT_PUBLIC_MQTT_PASSWORD=${NEXT_PUBLIC_MQTT_PASSWORD}
ENV NEXT_PUBLIC_MQTT_PROTOCOL=${NEXT_PUBLIC_MQTT_PROTOCOL}

# 构建应用
RUN npm run build

# 生产阶段 - 创建精简的生产镜像
FROM base AS runner
WORKDIR /app

ENV NODE_ENV=production

# 创建非root用户以提高安全性
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
USER nextjs

# 复制必要文件
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static

# 确保Cesium静态文件存在于公共目录
RUN mkdir -p ./public/cesium && \
    if [ ! -f ./public/cesium/Cesium.js ]; then \
    echo "警告: Cesium.js不存在，请检查构建过程" && \
    ls -la ./public/cesium || true; \
    fi

# 设置环境变量 - 这些可以在运行时被覆盖
ENV PORT 3500
ENV HOSTNAME "0.0.0.0"

# MQTT配置环境变量 - 运行时可覆盖
ENV NEXT_PUBLIC_MQTT_HOST=113.45.136.1
ENV NEXT_PUBLIC_MQTT_PORT=8083
ENV NEXT_PUBLIC_MQTT_USERNAME=admin
ENV NEXT_PUBLIC_MQTT_PASSWORD=admin123
ENV NEXT_PUBLIC_MQTT_PROTOCOL=ws

# 暴露端口
EXPOSE 3500

# 启动应用
CMD ["node", "server.js"] 